<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-input-search
            v-model="filterData.roleName"
            clearable
            placeholder="请输入角色名称"
            style="width: 100%"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
        </div>
        <div class="right-box">
          <!--          <el-button type="primary" :icon="EpSwitch" :loading="syncMenuBtnLoading" @click="handleSyncMenu">同步菜单</el-button> -->
          <el-button type="success" :icon="IconSolarAddCircleLinear" @click="handleAdd">新增</el-button>
        </div>
      </div>
    </template>
    <el-table ref="elTableRef" v-loading="baseData.loading" border height="100%" :data="tableData" showOverflowTooltip stripe style="width: 100%">
      <template #empty>
        <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
      </template>
      <el-table-column
        fixed
        type="index"
        :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
        label="编号"
        sortable
        width="60"
        align="center"
        headerAlign="center"
      ></el-table-column>
      <el-table-column fixed label="角色" prop="roleName" minWidth="120"></el-table-column>
      <el-table-column fixed label="数据范围" prop="dataScope" minWidth="120">
        <template #default="{ row }">
          {{ dataScopeList.find((v) => v.value === row.dataScope)?.label || '' }}
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" minWidth="180"></el-table-column>
      <el-table-column label="创建时间" prop="createTime" minWidth="120"></el-table-column>
      <el-table-column fixed="right" label="状态" width="90" align="center" headerAlign="center">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :disabled="row.admin"
            style="--el-switch-on-color: var(--el-color-success); --el-switch-off-color: var(--el-color-danger)"
            inlinePrompt
            activeText="已启用"
            inactiveText="已冻结"
            :activeValue="0"
            :inactiveValue="1"
            :loading="row._statusLoading"
            :beforeChange="() => handleSetStateSingle(row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="140" align="center" headerAlign="center">
        <template #default="{ row }">
          <el-button v-if="!row.admin" link type="danger" size="small" :icon="IconDelete" @click="handleDel(row)">删除</el-button>
          <el-button link type="primary" size="small" :icon="IconEdit" @click="openEdit(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
    <role-info ref="roleInfoRef"></role-info>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconSearch from '~icons/ep/search';
  import IconDelete from '~icons/ep/delete';
  import IconEdit from '~icons/ep/edit';
  import IconSolarAddCircleLinear from '~icons/solar/add-circle-linear';
  // import EpSwitch from '~icons/ep/switch';
  import RoleInfo from './components/role-info.vue';
  import { dataScopeList } from './data';
  import { type SysRole, type SysRoleListRequest, changeStatusRoleAxios, delRoleAxios, getSysRoleListAxios } from '@/api/permission-management';

  type _SysRole = SysRole & {
    /** 修改冻结状态的加载状态 */
    _statusLoading?: boolean;
  };
  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const roleInfoRef: $RefComp<typeof RoleInfo> = ref(null);
  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });

  const filterData: Ref<SysRoleListRequest> = ref<SysRoleListRequest>({
    roleName: '',
    current: 1,
    size: 40,
  });

  const tableData: Ref<_SysRole[]> = ref([]);
  const description = ref('');
  // const syncMenuBtnLoading = ref<boolean>(false);
  onMounted(() => {
    getAxiosData();
  });

  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      const res = await getSysRoleListAxios(filterData.value);
      tableData.value = res.data.records;
      description.value = '暂无数据';
      filterData.value.current = res.data.current;
      filterData.value.size = res.data.size;
      baseData.total = res.data.total;
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      tableData.value = [];
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  /** 编辑 */
  function openEdit(role: SysRole) {
    roleInfoRef.value?.show({
      type: 'edit',
      role,
      editCallBack: () => {
        getAxiosData(false);
      },
    });
  }

  /** 跳转到新增视频页面 */
  function handleAdd() {
    roleInfoRef.value?.show({
      type: 'add',
      addCallBack: () => {
        getAxiosData(false);
      },
    });
  }

  /** 同步菜单 */
  // async function handleSyncMenu() {
  //   try {
  //     syncMenuBtnLoading.value = true;
  //     await menuSyncAxios(transformationMenuHandler(prefixPathRoutes(getAppMainList(false))));
  //     syncMenuBtnLoading.value = false;
  //     ElToast.success('同步成功');
  //   } catch (error) {
  //     syncMenuBtnLoading.value = false;
  //     ElToast.error(error.msg || '同步失败，-BD004');
  //   }
  // }

  /** 删除 */
  function handleDel(row: _SysRole) {
    ElMessageBox.confirm('删除后不可恢复，您确定删除吗？', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
      beforeClose: async (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true;

          try {
            await delRoleAxios(row.roleId);
            await getAxiosData(false);
            instance.confirmButtonLoading = false;
            done();
            ElToast.success('删除成功');
          } catch (error) {
            instance.confirmButtonLoading = false;
            ElToast.error(error.msg || '删除失败，-BD004');
          }
        } else {
          done();
        }
      },
    });
  }

  /** 修改单个解冻状态 */
  async function handleSetStateSingle(row: _SysRole): Promise<boolean> {
    const name = row.status === 0 ? '冻结' : '启用';
    try {
      row._statusLoading = true;
      await changeStatusRoleAxios(row.roleId);
      row._statusLoading = false;
      ElToast.success(`${name}成功`);
      return Promise.resolve(true);
    } catch (error) {
      row._statusLoading = false;

      ElToast.error(error.msg || `${name}失败，-BD004`);
      return Promise.reject(false);
    }
  }

  /** 系统菜单转为接口接受格式 */
  // function transformationMenuHandler(menu: RouteRecordRaw[], res: MenuItem[] = []): MenuItem[] {
  //   for (const item of menu) {
  //     const data = {
  //       menuName: item.meta?.title,
  //       menuType: item.children ? 'D' : 'M',
  //       meta: {
  //         title: item.meta?.title || '',
  //       },
  //       path: item.path,
  //       children: [],
  //     };
  //     res.push(data);
  //     if (item.children && item.children.length > 0) {
  //       transformationMenuHandler(item.children, data.children);
  //     }
  //   }
  //   return res;
  // }
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      display: grid;
      flex: 1;
      grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
      grid-gap: 15px;
      margin-right: 15px;
    }
  }
</style>
